<template>
  <div style="width: 100%;">
    <h3>负载均衡监控</h3>
    <el-card shadow="always">
      <el-alert
        title="负载均衡状态"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 20px;"
      >
      </el-alert>
      <el-table :data="nodes" border style="width: 100%">
        <el-table-column prop="nodeId" label="节点ID" width="180"></el-table-column>
        <el-table-column prop="ip" label="IP地址"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span :class="{ 'status-normal': scope.row.status === '正常', 'status-failure': scope.row.status === '故障' }">
              {{ scope.row.status }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="load" label="负载"></el-table-column>
      </el-table>
    </el-card>
    <div ref="chart" style="width: 1024px; height: 400px; margin-top: 20px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: ['nodes'],
  name: "LoadBalancerMonitoring",
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.initChart();
  },
  watch: {
    nodes: {
      handler(newNodes) {
        this.updateChartData(newNodes);
      },
      deep: true
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      this.updateChartData(this.nodes);
    },
    updateChartData(nodes) {
      const option = {
        title: {
          text: '节点负载情况'
        },
        tooltip: {},
        legend: {
          data: ['负载']
        },
        xAxis: {
          data: nodes.map(node => `${node.ip}`)
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [{
          name: '负载',
          type: 'bar',
          data: nodes.map(node => parseInt(node.load.replace('%', '')))
        }]
      };
      this.chart.setOption(option);
      this.resizeChart();
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  }
};
</script>

<style scoped lang="scss">
h3 {
  margin-bottom: 20px;
}

.status-normal {
  color: green;
}

.status-failure {
  color: red;
}
</style>
